package com.aaa.arouterone.testOcr

import android.Manifest
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.aaa.arouterone.App.Companion.LOGTAG
import com.aaa.arouterone.R
import com.aaa.arouterone.testOcr.utils.*
import com.aaa.arouterone.utils.CameraUtils
import com.baidu.ocr.sdk.OCR
import com.baidu.ocr.sdk.OnResultListener
import com.baidu.ocr.sdk.exception.OCRError
import com.baidu.ocr.sdk.model.AccessToken
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.luck.picture.lib.tools.ToastUtils
import kotlinx.android.synthetic.main.activity_o_c_rbaidu_test.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions
import java.net.URLEncoder
import java.util.regex.Pattern


/**
 *  百度ocr 自定义模板测试
 *  @author lfc-LFC
 *  created at 2021/3/31 17:34
 */
class OCRbaiduTest : AppCompatActivity() {


    companion object {
        val CAMERA_PERMISSIONS = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
        const val OCRURL = "https://aip.baidubce.com/rest/2.0/solution/v1/iocr/recognise"

        /**
         * 通用模板id
         */
        const val templateSignID = "7a0cd8dfb07706ab4e85ad792aa543a4"
        const val TAKE_PHOTO = 1 //声明一个请求码，用于识别返回的结果

        const val KEY_CARNUM = "carNum"                 //运输卡车号
        const val KEY_SHIPPER_NAME = "shipperName"             // 货主名称
        const val KEY_CARD_NUM = "cardNum"                 //  检疫卡号
        const val KEY_SHIPPER_TEL = "shipperTel"          // 货主电话
        const val KEY_ANIMAL_SPECIES = "animalSpecies"           // 货物类别
        const val KEY_ANIMAL_COUNTS = "animalCounts"            //  货物数量
        const val KEY_ANIMAL_USE = "animalUse"          // 货物用途
        const val KEY_START_ADS = "startAddress"           // 开始地点
        const val KEY_END_ADS = "endAddress"             // 结束地点
        const val KEY_ANIMAL_NUM = "animalNum"           // 耳标号
    }

    private var job: Job? = null
    private var bdAccessToken: String = ""
    private var imageUri: Uri? = null

    private var proDialog: LoadingDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_o_c_rbaidu_test)
        initOcr()

        initView()
        initData()
    }

    private fun initView() {
        lay_show.visibility = View.GONE
        btn_start.setOnClickListener {
//        拍照获取图片位置

            checkCameraPermission(10086)
        }
        et_01.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                var strResult = s.toString()
                if (strResult.length < 7) {
                    et_01.setTextColor(Color.parseColor("#ff0000"))
                } else {
                    et_01.setTextColor(Color.parseColor("#000000"))

                }
            }

        })
        et_04.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                var strResult = s.toString()
                if (strResult.length < 11) {
                    et_04.setTextColor(Color.parseColor("#ff0000"))
                } else {
                    if (validateMobilePhone(strResult))
                        et_04.setTextColor(Color.parseColor("#000000"))
                    else
                        et_04.setTextColor(Color.parseColor("#ff0000"))
                }
            }

        })

    }


    private fun checkCameraPermission(requestCode: Int) {
        if (EasyPermissions.hasPermissions(this, *CAMERA_PERMISSIONS)) {
//启动拍照
            requestCamera()
        } else {
            EasyPermissions.requestPermissions(this, "应用需要访问相机权限", requestCode, *CAMERA_PERMISSIONS)
        }

    }

    private fun initData() {


    }

    /**
     *
     *  0 accessToken  bdAccessToken
     *  1 image/url  base64图片资源
     *  2 templateSign  模板 ID
     *  3 classifierId  分类器Id，
     *
     */


    /**
     * 采用httpclient post数据到服务器
     */

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            10086 -> {
                if (EasyPermissions.hasPermissions(this, *CAMERA_PERMISSIONS)) {
//启动拍照
                    requestCamera()
                }
            }
            else -> {
            }
        }


    }

    private fun initOcr() {
        showLoading("正在初始化识别组件....", false)

        OCR.getInstance(this).initAccessToken(
            object : OnResultListener<AccessToken> {

                override fun onError(error: OCRError) {
                    // 调用失败，返回OCRError子类SDKError对象
                    Log.d(LOGTAG, "onError" + error.toString())
//                    tvInfo.setText(error.toString())
                    Toast.makeText(
                        this@OCRbaiduTest,
                        "识别组件初始化失败： " + error.toString(),
                        Toast.LENGTH_LONG
                    ).show()
                    hideLoading()
                }

                override fun onResult(result: AccessToken?) {
                    // 调用成功，返回AccessToken对象
                    bdAccessToken = result?.accessToken.toString()
                    Log.d(LOGTAG, "onResult:" + bdAccessToken)
//                    tvInfo.setText(bdAccessToken.toString())
                    hideLoading()

                }
            }, applicationContext
        )
    }

    private fun requestCamera() {
        CameraUtils.OpenCameraMore(this, 0, 0, 1, object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: MutableList<LocalMedia>?) {
                showLoading("正在压缩图片....", false)
                var imgPath: String = ""

                result?.forEach {
                    if (imgPath.isNullOrBlank()) {
                        imgPath =
                            if (it.compressPath.isNullOrBlank()) it.realPath else it.compressPath

                    }
                }
                Log.d(LOGTAG, "imgPath:" + imgPath)
                ImgShowUtils().showImgs(this@OCRbaiduTest, iv_show, imgPath)
//                GlideUtils.ShowImgHead(this@OCRbaiduTest, iv_show, imgPath)
                dealImgData(imgPath)
            }

            override fun onCancel() {
            }
        })

    }


    private fun dealImgData(imgPath: String) {
        setLoadingMsg("正在解析图片....")

        job = GlobalScope.launch {
            try {
                Log.d(LOGTAG, "imgPath:  " + imgPath)
                var imgData = FileUtil.readFileByBytes(imgPath);
                var imgStr = baseEncodeDeal(imgData)
                // 请求模板参数
                var recogniseParams = getRecogniseParams(imgStr)
                // 请求分类器参数
//            var classifierParams =
//                "classifierId=你创建的分类器的ID&image=" + URLEncoder.encode(imgStr, "UTF-8");

                var auth = bdAccessToken;
                Log.d(LOGTAG, "OCRURL  " + OCRURL)
                Log.d(LOGTAG, "auth  " + auth)
                Log.d(LOGTAG, "recogniseParams  " + recogniseParams)

                // 请求模板识别
                var result = HttpUtil.post(OCRURL, auth, recogniseParams);
                Log.d(LOGTAG, "result  " + result.toString())
                var resultMap = getValueForResult(result)
                setLoadingMsg("正在分析结果....")

            } catch (e: Exception) {
                e.printStackTrace()
                hideLoading()
            }

        }
    }

    var sb = StringBuilder()
    private fun upDataForUI(resultMap: java.util.HashMap<String, String>) {
        hideLoading()

        runOnUiThread {
            resultMap?.apply {
                var strCarNum = resultMap[KEY_CARNUM]//运输卡车号
                var strShipperName = resultMap[KEY_SHIPPER_NAME]// 货主名称
                var strCardNum = resultMap[KEY_CARD_NUM]//  检疫卡号
                var strShipperTel = resultMap[KEY_SHIPPER_TEL]// 货主电话
                var strAnimalSpecies = resultMap[KEY_ANIMAL_SPECIES]    // 货物类别
                var strAnimalCounts = resultMap[KEY_ANIMAL_COUNTS]    //  货物数量
                var strAnimalUse = resultMap[KEY_ANIMAL_USE]// 货物用途
                var strStartAds = resultMap[KEY_START_ADS]// 开始地点
                var strEndAds = resultMap[KEY_END_ADS]// 结束地点
                var strAnimalNum = resultMap[KEY_ANIMAL_NUM]// 耳标号
                et_01.setText(strCarNum)
                et_02.setText(strShipperName)
                et_03.setText(strCardNum)
                et_04.setText(strShipperTel)
                et_05.setText(strAnimalSpecies)
                try {
                    et_06.setText(Chinese2Num.ChineseConvertToNumber(strAnimalCounts))

                } catch (e: Exception) {
                    e.printStackTrace()
//                    et_03.inputType= Typeface.NORMAL
                    et_06.setText(0.toString())
                }
                et_07.setText(strAnimalUse)
                et_08.setText(strStartAds)
                et_09.setText(strEndAds)
                et_10.setText(strAnimalNum)
                lay_show.visibility = View.VISIBLE
                /* sb.append("运输卡车：$strCarNum\n")
                 sb.append("货主名称：$strShipperName\n")
                 sb.append("检疫卡号：$strCardNum\n")
                 sb.append("货主电话：$strShipperTel\n")
                 sb.append("货物类别：$strAnimalSpecies\n")
                 sb.append("货物数量：$strAnimalCounts\n")
                 sb.append("货物用途：$strAnimalUse\n")
                 sb.append("开始地点：$strStartAds\n")
                 sb.append("结束地点：$strEndAds\n")
                 sb.append("耳标号：  $strAnimalNum\n")
                 tvInfo.text = sb*/
//                tvInfo.invalidate()
            }

        }
    }

    var handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                12 -> {
                    var strMsg: String = msg.obj as String
                    Toast.makeText(this@OCRbaiduTest, strMsg, Toast.LENGTH_LONG).show()
                }
                else -> {
                }
            }


        }
    }

    private fun getValueForResult(result: String?): HashMap<String, String> {
        var resultMap = hashMapOf<String, String>()

        try {
            var jsonInfo = JSONObject(result)
            var errorCode = -1
            var errorMsg = "获取失败....请重试！"
            if (jsonInfo.has("error_code")) {
                errorCode = jsonInfo.getInt("error_code")
            }
            if (jsonInfo.has("error_msg")) {
                errorMsg = jsonInfo.getString("error_msg")
            }
            if (errorCode != 0) {
                var msg = Message.obtain()
                msg.what = 12
                msg.obj = errorMsg
                handler.sendMessage(msg)
//                Toast.makeText(this, errorMsg, Toast.LENGTH_LONG).show()
                return resultMap
            }
//            判空
            if (!jsonInfo.has("data")) {
                var msg = Message.obtain()
                msg.what = 12
                msg.obj = errorMsg
                handler.sendMessage(msg)
//                Toast.makeText(this, errorMsg, Toast.LENGTH_LONG).show()
                hideLoading()

                return resultMap
            }
            var objData = jsonInfo.getJSONObject("data")
//          判空
            if (!objData.has("ret")) {
                var msg = Message.obtain()
                msg.what = 12
                msg.obj = errorMsg
                handler.sendMessage(msg)
//                Toast.makeText(this, errorMsg, Toast.LENGTH_LONG).show()
                hideLoading()
                return resultMap
            }
            var jsonArrays = objData.getJSONArray("ret")
            for (index in 0 until jsonArrays.length()) {
                var childJsonObj = jsonArrays[index] as JSONObject
                var wordName = "" //识别字段
                var wordValue = ""// 识别内容
                if (childJsonObj.has("word_name")) {
                    wordName = childJsonObj.getString("word_name")
                }
                if (wordName.isNullOrBlank()) {
                    continue
                }
                if (childJsonObj.has("word")) {
                    wordValue = childJsonObj.getString("word")
                }
                resultMap.put(wordName, wordValue)
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }
        upDataForUI(resultMap)
        return resultMap

    }

    suspend fun baseEncodeDeal(imgData: ByteArray): String {
        return Base64Util.encode(imgData);
    }

    suspend fun getRecogniseParams(imgStr: String): String {
//        return "templateSign=7a0cd8dfb07706ab4e85ad792aa543a4" + URLEncoder.encode(imgStr, "UTF-8");
        return "templateSign=7a0cd8dfb07706ab4e85ad792aa543a4&image=" + URLEncoder.encode(
            imgStr,
            "UTF-8"
        );
    }

    override fun onDestroy() {
        super.onDestroy()
        job?.cancel()
    }

    //显示等待框
    fun showLoading(msg: String?, touch: Boolean) {
        if (proDialog == null) {
            proDialog = LoadingDialog()
        } else {
            proDialog?.dismiss()
        }
        proDialog?.setMsg(msg.toString())
            ?.setOnTouchOutside(touch)
            ?.show(supportFragmentManager, "loading")
        //fragment的话就把getSupportFragmentManager参数换成getChildFragmentManager
    }

    //动态修改等待框中的文字
    fun setLoadingMsg(msg: String?) {
        if (proDialog == null) {
            return
        }
        proDialog?.setMsg(msg)
    }

    //隐藏等待框
    fun hideLoading() {
        if (proDialog != null) {
            proDialog?.dismiss()
        }
    }

    fun isCarnumberNO2(carnumber: String): Boolean {
        /*
     车牌号格式：汉字 + A-Z + 位A-Z或-
     （只包括了普通车牌号，教练车和部分部队车等车牌号不包括在内）
             val pattern: Pattern = Pattern.compile("^[1]\\d{10}$")

     */
//        val carnumRegex = "[\\ue-\\ufa]{}[A-Z]{}[A-Z_-]{}"
//        return if (TextUtils.isEmpty(carnumber)) false else carnumber.matches(carnumRegex)
        return false
    }

    fun validateMobilePhone(`in`: String?): Boolean {
        val pattern: Pattern = Pattern.compile("^[1]\\d{10}$")
        return pattern.matcher(`in`).matches()
    }

    /*  fun isCarnumberNO(str: String?): Boolean {
          val pattern: Pattern = Pattern.compile("^[\ue-\ufa]{}[A-Z]{}[A-Z_-]{}$")
          return pattern.matcher(str).matches()
      }*/
}